package com.music.note_android.ui.editor

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.music.note_android.R
import com.music.note_android.ui.editor.DrawingTool

/**
 * 绘图工具栏组件
 * 提供工具选择、颜色选择、粗细调节等功能
 */
class DrawingToolbar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    // UI组件
    private lateinit var btnPen: ImageButton
    private lateinit var btnPencil: ImageButton
    private lateinit var btnHighlighter: ImageButton
    private lateinit var btnEraser: ImageButton
    private lateinit var currentColorIndicator: View
    private lateinit var btnColorPicker: ImageButton
    private lateinit var seekbarBrushSize: SeekBar
    private lateinit var tvBrushSize: TextView
    private lateinit var btnUndo: ImageButton
    private lateinit var btnRedo: ImageButton
    private lateinit var btnClear: ImageButton

    // 当前状态
    private var currentTool: DrawingTool = DrawingTool.PEN
    private var currentColor: Int = Color.BLACK
    private var currentBrushSize: Float = 6f
    private var canUndo: Boolean = false
    private var canRedo: Boolean = false

    // 回调接口
    private var toolbarListener: ToolbarListener? = null
    private var actionListener: OnToolbarActionListener? = null

    init {
        initView()
        setupListeners()
        updateToolSelection()
        updateColorIndicator()
        updateBrushSizeDisplay()
    }

    private fun initView() {
        LayoutInflater.from(context).inflate(R.layout.toolbar_drawing, this, true)
        
        btnPen = findViewById(R.id.btn_pen)
        btnPencil = findViewById(R.id.btn_pencil)
        btnHighlighter = findViewById(R.id.btn_highlighter)
        btnEraser = findViewById(R.id.btn_eraser)
        currentColorIndicator = findViewById(R.id.current_color_indicator)
        btnColorPicker = findViewById(R.id.btn_color_picker)
        seekbarBrushSize = findViewById(R.id.seekbar_brush_size)
        tvBrushSize = findViewById(R.id.tv_brush_size)
        btnUndo = findViewById(R.id.btn_undo)
        btnRedo = findViewById(R.id.btn_redo)
        btnClear = findViewById(R.id.btn_clear)
    }

    private fun setupListeners() {
        // 工具选择监听
        btnPen.setOnClickListener { selectTool(DrawingTool.PEN) }
        btnPencil.setOnClickListener { selectTool(DrawingTool.PENCIL) }
        btnHighlighter.setOnClickListener { selectTool(DrawingTool.HIGHLIGHTER) }
        btnEraser.setOnClickListener { selectTool(DrawingTool.ERASER) }

        // 颜色选择监听
        btnColorPicker.setOnClickListener {
            toolbarListener?.onColorPickerClicked(currentColor)
        }

        // 粗细调节监听
        seekbarBrushSize.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    // 将进度值(0-100)映射到画笔大小(1-50)
                    currentBrushSize = (progress * 0.49f + 1f)
                    updateBrushSizeDisplay()
                    toolbarListener?.onBrushSizeChanged(currentBrushSize)
                    actionListener?.onStrokeWidthChanged(currentBrushSize)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 操作按钮监听
        btnUndo.setOnClickListener {
            if (canUndo) {
                toolbarListener?.onUndoClicked()
                actionListener?.onUndoRequested()
            }
        }

        btnRedo.setOnClickListener {
            if (canRedo) {
                toolbarListener?.onRedoClicked()
                actionListener?.onRedoRequested()
            }
        }

        btnClear.setOnClickListener {
            toolbarListener?.onClearClicked()
            actionListener?.onClearRequested()
        }
    }

    private fun selectTool(tool: DrawingTool) {
        if (currentTool != tool) {
            currentTool = tool
            updateToolSelection()
            toolbarListener?.onToolChanged(tool)
            actionListener?.onToolSelected(tool)
        }
    }

    private fun updateToolSelection() {
        // 重置所有工具按钮状态
        btnPen.isSelected = false
        btnPencil.isSelected = false
        btnHighlighter.isSelected = false
        btnEraser.isSelected = false

        // 设置当前选中工具
        when (currentTool) {
            DrawingTool.PEN -> btnPen.isSelected = true
            DrawingTool.PENCIL -> btnPencil.isSelected = true
            DrawingTool.HIGHLIGHTER -> btnHighlighter.isSelected = true
            DrawingTool.ERASER -> btnEraser.isSelected = true
        }

        // 根据工具类型显示/隐藏颜色选择器
        val showColorPicker = currentTool != DrawingTool.ERASER
        currentColorIndicator.visibility = if (showColorPicker) View.VISIBLE else View.GONE
        btnColorPicker.visibility = if (showColorPicker) View.VISIBLE else View.GONE
    }

    private fun updateColorIndicator() {
        currentColorIndicator.setBackgroundColor(currentColor)
    }

    private fun updateBrushSizeDisplay() {
        tvBrushSize.text = String.format("%.0f", currentBrushSize)
    }

    // 公共方法
    fun setCurrentTool(tool: DrawingTool) {
        selectTool(tool)
    }

    fun getCurrentTool(): DrawingTool = currentTool

    fun setCurrentColor(color: Int) {
        currentColor = color
        updateColorIndicator()
        toolbarListener?.onColorChanged(color)
        actionListener?.onColorSelected(color)
    }

    fun getCurrentColor(): Int = currentColor

    fun setBrushSize(size: Float) {
        currentBrushSize = size.coerceIn(1f, 50f)
        // 将画笔大小(1-50)映射到进度值(0-100)
        val progress = ((currentBrushSize - 1f) / 0.49f).toInt()
        seekbarBrushSize.progress = progress
        updateBrushSizeDisplay()
    }

    fun getBrushSize(): Float = currentBrushSize

    fun setUndoRedoState(canUndo: Boolean, canRedo: Boolean) {
        this.canUndo = canUndo
        this.canRedo = canRedo
        btnUndo.isEnabled = canUndo
        btnRedo.isEnabled = canRedo
        btnUndo.alpha = if (canUndo) 1.0f else 0.5f
        btnRedo.alpha = if (canRedo) 1.0f else 0.5f
    }

    fun setToolbarListener(listener: ToolbarListener) {
        this.toolbarListener = listener
    }
    
    fun setOnToolbarActionListener(listener: OnToolbarActionListener) {
        this.actionListener = listener
    }

    /**
     * 工具栏事件监听接口
     */
    interface OnToolbarActionListener {
        fun onToolSelected(tool: DrawingTool)
        fun onColorSelected(color: Int)
        fun onStrokeWidthChanged(width: Float)
        fun onUndoRequested()
        fun onRedoRequested()
        fun onClearRequested()
    }
    
    // 保持向后兼容的旧接口
    interface ToolbarListener {
        fun onToolChanged(tool: DrawingTool)
        fun onColorChanged(color: Int)
        fun onColorPickerClicked(currentColor: Int)
        fun onBrushSizeChanged(size: Float)
        fun onUndoClicked()
        fun onRedoClicked()
        fun onClearClicked()
    }

    /**
     * 工具栏状态数据类
     */
    data class ToolbarState(
        val currentTool: DrawingTool,
        val currentColor: Int,
        val brushSize: Float,
        val canUndo: Boolean,
        val canRedo: Boolean
    )

    fun getToolbarState(): ToolbarState {
        return ToolbarState(
            currentTool = currentTool,
            currentColor = currentColor,
            brushSize = currentBrushSize,
            canUndo = canUndo,
            canRedo = canRedo
        )
    }

    fun restoreToolbarState(state: ToolbarState) {
        setCurrentTool(state.currentTool)
        setCurrentColor(state.currentColor)
        setBrushSize(state.brushSize)
        setUndoRedoState(state.canUndo, state.canRedo)
    }
}